package com.bgds.sys.rbac.serviceimpl;

import com.bgds.sys.common.base.BaseDao;
import com.bgds.sys.rbac.dao.UserDao;
import com.bgds.sys.rbac.dao.UserRoleDao;
import com.bgds.sys.rbac.domain.User;
import com.bgds.sys.rbac.domain.UserRole;
import com.bgds.sys.rbac.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户业务实现类
 * @author lj
 */
@Slf4j
@Service
@Transactional(rollbackOn = Exception.class)
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;


    @Override
    public BaseDao<User, Long> getRepository() {
        return userDao;
    }


    /**
     * 条件查询账号列表
     * @param key
     * @param pageable
     * @return
     */
    @Override
    public Page<User> listByCondition(String key, Pageable pageable){
        Specification<User> specification = (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            //模糊搜素
            if (StringUtils.isNotBlank(key)) {
                Predicate descriptionPredicate = cb.like(root.get("username").as(String.class), "%" + key + "%");
                Predicate namePredicate = cb.like(root.get("userId").as(String.class), "%" + key + "%");
                Predicate p = cb.and(cb.or(descriptionPredicate, namePredicate));
                predicates.add(cb.or(p));
            }
            Predicate[] pre = new Predicate[predicates.size()];
            return query.where(predicates.toArray(pre)).getRestriction();
        };
        Page<User> userPage=userDao.findAll(specification,pageable);

        return userPage;

    }

    /**
     * 更新用户角色
     * @param userId
     * @param roleId
     */
    @Override
    public void updateUserRole(Long userId,Long roleId){
          userRoleDao.deleteByUserId(userId);

            UserRole ur=new UserRole();
            ur.setRoleId(roleId);
            ur.setUserId(userId);
            userRoleDao.save(ur);


    }


}
